<?php
/**
 * 后台基础控制器
 * Created by PhpStorm.
 * User: yhz
 * Date: 2017-12-19
 * Time: 17:11
 */

namespace app\admin\controller;


use app\admin\auth\Auth;
use app\admin\auth\Tree;
use app\common\model\AdminUsers;
use think\Controller;
use think\Request;
use think\Session;

class BaseController extends Controller
{
    protected $request, $request_type, $param, $post, $get, $module, $controller, $action, $url, $do_url, $id, $web_data, $api_result, $model;
    public function __construct()
    {
        $this->request      = Request::instance();
        $this->request_type = $this->request->isGet() ? 1 : (
        $this->request->isPost() ? 2 : (
        $this->request->isPut() ? 3 : (
        $this->request->isDelete() ? 4 : 0
        )));
        $this->param      = $this->request->param();
        $this->post       = $this->request->post();
        $this->get        = $this->request->get();
        $this->module     = $this->request->module();
        $this->controller = $this->request->controller();
        $this->action     = $this->request->action();
        $this->do_url     = $this->parseName($this->module) . "/" . $this->parseName($this->controller) . "/";
        $this->url        = $this->parseName($this->module) . '/' . $this->parseName($this->controller) . "/" . $this->parseName($this->action);
        $this->id         = isset($this->param['id']) ? $this->param['id'] : -1;
        $this->api_result = [
            'status'    => 404,
            'extend'    => [],
            'result'    => [],
            'message'   => '',
            'timestamp' => time()
        ];
        parent::__construct();
    }
    public function _initialize()
    {

        $auth = new Auth();
        $this->web_data['test'] = 'aaa';

        if (Auth::is_login()) {
            $user_id = Session::get('user.user_id');
            if ($user_id!=1) {
                //执行权限检查
                if (!$auth->check($this->url,$user_id)) {
                    //无权限
                    $this->do_error('无权限');
                }
            }
            $this->web_data['left_menu'] = $this->getLeftMenu();//获取左侧菜单
            $user_info                   = $this->getUserInfo($user_id);
            $this->web_data['user_info'] = $user_info;//获取用户信息
        }else{
            $this->redirect('pub/login');
        }

    }

    //获取用户信息
    protected function getUserInfo($user_id)
    {
        $user_info = AdminUsers::get($user_id);
        return $user_info;
    }
    /***
     * 生成左侧菜单
     * @return string
     */
    protected function getLeftMenu()
    {
        $auth = new Auth();
        $menu = $auth->getMenuList(Session::get('user.user_id'), 1);
        $max_level  = 0;
        $current_id = 1;
        $parent_ids = array(0 => 0);
        $current_nav = ['', ''];
        foreach ($menu as $k => $v) {
            if ($v['url'] == $this->url) {
                $parent_ids  = $this->getMenuParent($menu, $v['menu_id']);
                $current_id  = $v['menu_id'];
                $current_nav = $this->getCurrentNav($menu, $v['menu_id']);
            }
        }
        if ($parent_ids == false) {
            $parent_ids = array(0 => 0);
        }
        $this->web_data['current_nav'] = $current_nav[1];
        $tree = new Tree();
        foreach ($menu as $k => $v) {
            $url               = url($v['url']);
            $menu[$k]['icon']  = !empty($v['icon']) ? $v['icon'] : 'fa fa-list';
            $menu[$k]['level'] = $tree->get_level($v['menu_id'], $menu);
            $max_level         = $max_level <= $menu[$k]['level'] ? $menu[$k]['level'] : $max_level;
            $menu[$k]['url']   = $url;
        }

        $father_menu = [];
        $child_menu=[];
        foreach ($menu as $k => $v) {
            if ($menu[$k]['level']==0) {
                array_push($father_menu,$menu[$k]);
            }
        }
        foreach ($menu as $k => $v) {
            if ($menu[$k]['level']!=0) {
                array_push($child_menu,$menu[$k]);
            }
        }

        foreach ($child_menu as $k => $v) {
            foreach ($father_menu as $i => $n) {
                if ($child_menu[$k]['parent_id']==$father_menu[$i]['menu_id']) {
                    $father_menu[$i]['child'][] = $child_menu[$k];
                    break;
                }
            }
        }




        $html ="";
        foreach ($father_menu as $k=>$v) {
            $nav_url = $father_menu[$k]['url'];
            $nav_title= $father_menu[$k]['title'];
            $nav_icon= $father_menu[$k]['icon'];
            $nav_id = $father_menu[$k]['menu_id'];
            if (array_key_exists('child',$father_menu[$k])) {
                $html = $html . "<li class='layui-nav-item '><a class='' href='javascript:;'><i class='iconfont'>$nav_icon</i><span>$nav_title</span></a><dl class='layui-nav-child'>";
                foreach ($father_menu[$k]['child'] as $i=>$n) {
                    $c_nav_url = $n['url'];
                    $c_nav_title= $n['title'];
                    $c_nav_icon= $n['icon'];
                    $c_nav_id = $n['menu_id'];
                    $html=$html."<dd><a href='javascript:;' data-navid='$c_nav_id' onclick='chageTab(this)' data-nav='{\"url\":\"$c_nav_url\",\"title\":\"$c_nav_title\"}'><i class='iconfont'>$c_nav_icon</i><span>$c_nav_title</span></a></dd>";
                }
                $html = $html . '</dl></li>';

            } else {
                $html =$html."<li class='layui-nav-item'>
                <a  data-navid='$nav_id' href='javascript:;' onclick='chageTab(this)' data-nav='{\"url\":\"$nav_url\",\"title\":\"$nav_title\"}'>
                <i class='iconfont'>$nav_icon</i><span>$nav_title</span></a>
                </li>";
            }

        }
        return $html;
    }

    /**
     * 添加，修改时返回错误信息方法
     * @param string $msg
     * @param null $url
     * @param string $data
     */
    protected function do_error($msg = '操作失败', $url = null, $data = '')
    {
        $server = $this->request->server();
//        if ($url == null && isset($server['HTTP_REFERER'])) {
//            $url = $server['HTTP_REFERER'];
//        }
        $url = 'admin/errorpag/index';

        $current_url = $server['REQUEST_SCHEME'] . $server['SERVER_NAME'] . $server['REQUEST_URI'];
        if ($url == $current_url || $this->url == '' || $url == null) {
            $msg = '页面不存在！';
            $url = 'admin/index/index';
        }
        return $this->redirect($url, $data, 302, ['error_message' => $msg,'form_info'=>$this->param]);
    }

    /***
     * 重写父类的fetch方法，将页面数据传给公共模板
     * @param string $template
     * @param array $vars
     * @param array $replace
     * @param array $config
     * @return mixed
     */
    protected function fetch($template = '', $vars = [], $replace = [], $config = [])
    {
        parent::assign(['web_data' => $this->web_data]);
        return parent::fetch($template, $vars, $replace, $config);
    }

    /**
     * 字符串命名风格转换
     * type 0 将Java风格转换为C的风格 1 将C风格转换为Java的风格
     * @param string $name 字符串
     * @param integer $type 转换类型
     * @param bool $ucfirst 首字母是否大写（驼峰规则）
     * @return string
     */
    protected function parseName($name, $type = 0, $ucfirst = true)
    {
        if ($type) {
            $name = preg_replace_callback('/_([a-zA-Z])/', function ($match) {
                return strtoupper($match[1]);
            }, $name);
            return $ucfirst ? ucfirst($name) : lcfirst($name);
        } else {
            return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_"));
        }
    }

    protected function getMenuParent($arr, $myid, $parent_ids = array())
    {
        $a = $newarr = array();
        if (is_array($arr)) {
            foreach ($arr as $id => $a) {
                if ($a['menu_id'] == $myid) {
                    if ($a['parent_id'] != 0) {
                        array_push($parent_ids, $a['parent_id']);
                        $parent_ids = $this->getMenuParent($arr, $a['parent_id'], $parent_ids);
                    }
                }
            }
        }
        return !empty($parent_ids) ? $parent_ids : false;
    }
    protected function getCurrentNav($arr, $myid, $parent_ids = array(), $current_nav = '')
    {
        $a = $newarr = array();
        if (is_array($arr)) {
            foreach ($arr as $id => $a) {
                if ($a['menu_id'] == $myid) {
                    if ($a['parent_id'] != 0) {
                        array_push($parent_ids, $a['parent_id']);
                        $ru          = '<li><a><i class="fa ' . $a['icon'] . '"></i> ' . $a['title'] . '</a></li>';
                        $current_nav = $ru . $current_nav;
                        $temp_result = $this->getCurrentNav($arr, $a['parent_id'], $parent_ids, $current_nav);
                        $parent_ids  = $temp_result[0];
                        $current_nav = $temp_result[1];
                    }
                }
            }
        }
        return !empty([$parent_ids, $current_nav]) ? [$parent_ids, $current_nav] : false;
    }
}